package com.haut.demo;

import com.haut.domain.Stu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class CacheDemo {
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate=jdbcTemplate;
    }

    @Cacheable(value = "allStus")
    public List<Stu> query() {
        List<Stu> stus = jdbcTemplate.query("select * from stu", (rs, row) -> {
            Stu stu = new Stu();
            stu.setId(rs.getLong("id"));
            stu.setUsername(rs.getString("username"));
            stu.setPass(rs.getString("pass"));
            stu.setJava(rs.getInt("java"));
            stu.setMath(rs.getInt("math"));
            stu.setOs(rs.getInt("os"));
            return stu;
        });
        log.debug("--query db--");
        return stus;
    }

    @CacheEvict(value="allStus",allEntries = true)
    public void update(){
        jdbcTemplate.update("update stu set java=? where id=?",1,3L);
    }

}
